package com.lzx.adx.report.controller.v1.meitu;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.bean.property.AdConfig;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.EventTypeEnums;
import com.lzx.adx.report.enums.MeituEventTypeEnums;
import com.lzx.adx.report.model.huawei.request.HwReportRequest;
import com.lzx.adx.report.model.huawei.request.HwUploadRequest;
import com.lzx.adx.report.model.meitu.request.MeituRequest;
import com.lzx.adx.report.model.meitu.request.MeituUploadReqeust;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.HwSecureUtil;
import com.lzx.adx.report.util.UrlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 美图广告上报
 */
@RequestMapping("/meitu/")
@RestController
@Slf4j
@RequiredArgsConstructor
public class MeiTuReportController {


    @Autowired
    private  ReportService reportService;

    @Autowired
    private  ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private  ReportMapper reportMapper;






    @GetMapping("/report")
    public ResponseEntity meituReqport(MeituRequest meituRequest, HttpServletRequest request){

      log.info("接收到【美图】的请求参数为{}", JsonUtils.toJsonString(meituRequest));
       //1.收到监测的数据存储
        ReportDTO reportDTO=reportMapper.toReportDTO(meituRequest);
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(meituRequest));
        if(StringUtils.isNotBlank(meituRequest.getMt_link_source())){
            String eventType=  meituRequest.getMt_link_source().equals("explosure")?"imp":"click";
            reportDTO.setEventType(eventType);
        }
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });

      //2.从缓存加载配置
      AccountDTO accountDTO = AccountLocalCache.getInstance().get(meituRequest.getDspId());

      //3.处理参数和URL
      String resultUrl= UrlUtil.handMeituUrl(reportDTO,accountDTO);
      log.info("账户号为{}，完整的小红书请求地址为{}",meituRequest.getDspId(),resultUrl);
       //2.2调用饿了嘛，上报接口
      String body = HttpUtil.createGet(resultUrl).execute().body();
      log.info("账户号为{}，上报小红书的接口，响应的结果为{}",meituRequest.getDspId(),body);
      JSONObject jsonObject=JSONObject.parseObject(body);
      //响应状态码成功
      if(jsonObject.getInteger("code").equals(0)){
          return ResponseEntity.ok(new Result());
      }else{
          return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
      }
    }


    /**
     * 小红书回传
     * @param click_id 请求事件ID
     * @param conv_type 转换类型
     * @param conv_ts 转换时间
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId,String click_id,String  conv_type,String conv_ts) throws Exception {
        if(StringUtils.isNotBlank(requestId)){
            click_id=requestId;
        }
         log.info("接收了小红书回调信息，请求流水号{},回调类型为{}，回调时间{}",click_id,conv_type,conv_ts);
         if(StringUtils.isBlank(conv_ts) || StringUtils.isBlank(conv_type)){
             log.info("请求参数异常，event_type{},event_time{]",conv_type,conv_ts);
             return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
         }

         //1.把转换结果更新到数据库
         Map<String,Object> params=new HashMap<>();
         params.put("bizRequestId",click_id);
         List<ReportDTO> list = reportService.list(params);
         ReportDTO reportDTO;
         if(CollectionUtil.isNotEmpty(list)){
              reportDTO = list.get(0);
              reportDTO.setResultType(conv_type);
              reportDTO.setResultTime(conv_ts);
              reportDTO.setUpdateTime(new Date());
              reportService.updateData(reportDTO,conv_type);
         }else{
             log.error("当前流水号，系统当前不存在");
             return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
         }

         log.info("从数据库查询的数据为{}",JsonUtils.toJsonString(reportDTO));

        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        MeituRequest meituRequest=JsonUtils.parseObject(reportDTO.getExtend(),MeituRequest.class);

        Map<String,Object> paramsReq=new HashMap<>();
        paramsReq.put("os",meituRequest.getOs());
        paramsReq.put("callback",reportDTO.getCallback());
        paramsReq.put("ad_id",reportDTO.getAdgroupId());
        paramsReq.put("customer_id","5010");
        paramsReq.put("muid",handMuid(meituRequest));
        paramsReq.put("uniid",meituRequest.getUniid());
        paramsReq.put("event_type",MeituEventTypeEnums.getXhsCodeByMtu(conv_type));
        paramsReq.put("conv_time",conv_ts);


        String urlParams = URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        String finalResultUrl=accountDTO.getSspApiUrl()+"?"+urlParams;
//        String sign= SecureUtil.md5(finalResultUrl+accountDTO.getSspKey());
//        String resultUrl = UrlUtil.handMeitu(finalResultUrl, sign);

        log.info("给美图上报回传结果，完整的URl{}",finalResultUrl);
         HttpRequest body = HttpUtil.createGet(finalResultUrl);
         String result = body.execute().body();
         log.info("dsp账户ID{}，接收美图转换响应的结果为{}",accountDTO.getId(),result);
         JSONObject jsonObject=JSONObject.parseObject(result);
         Integer resultCode = jsonObject.getInteger("status");
         if(resultCode==0){
             return ResponseEntity.ok(new Result());
         }else{
             return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new Result<>().error());
         }
   }

    private String handMuid(MeituRequest meituRequest) {
        if(StringUtils.isNotBlank(meituRequest.getImei()) && !(meituRequest.getImei().equals("__IMEI__")) ) {
            return meituRequest.getImei();
        }else if(StringUtils.isNotBlank(meituRequest.getHash_android_id()) && !(meituRequest.getHash_android_id().equals("__ANDROIDID__")) ){
            return meituRequest.getHash_android_id();
        }else{
            return meituRequest.getOaid();
        }
    }


}
